package com.tiles.tools;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

public class DesUtil {
    public static String encryption(String encryptiontext, String encryptKey)throws Exception{
        //    明文
        String encryption=encryptiontext;
        //密钥
        String encryptionKey= encryptKey;

        String text = encrypt(encryption, encryptionKey);

        //返回加密后的数据
        return text;
    }
    public static    String desDecry(String encryptiontext, String encryptKey)throws Exception{
        //明文
        String text=encryptiontext;
        //密钥
        String encryptionKey= encryptKey;

        String decry = decrytion(text, encryptionKey);
        //返回解密后的数据
        return decry;
    }

    private static String decrytion(String text, String encryptionKey) throws Exception {
        //   获得加密工具类对象
        Cipher cipher = Cipher.getInstance("DES");
        //初始化工具类
        SecretKeySpec key1 =getKey(encryptionKey);
        cipher.init(Cipher.DECRYPT_MODE,key1);
         //  将Base64 转为byte数组
        byte[] decode = Base64.getDecoder().decode(text);
            //   解密
       byte[] bytes= cipher.doFinal(decode);
        //返回解密后的数据
        return new String(bytes);
    }

    private static String encrypt(String encryption, String buffer) throws Exception{
        //获得加密工具类对象
        Cipher cipher = Cipher.getInstance("DES");

       // 初始化 mode：加密or解密
       SecretKeySpec key=getKey(buffer);
        cipher.init(Cipher.ENCRYPT_MODE,key);
        //用加密工具类对明文加密
        byte[] doFinal = cipher.doFinal(encryption.getBytes());
        //返回加密后的数据
        return new String(Base64.getEncoder().encode(doFinal));
    }

    private static SecretKeySpec getKey(String encryptionKey) {
        byte[] buffer = new byte[8];
        byte[] keyBytes = encryptionKey.getBytes();
        for (int i = 0; i < 8 && i < keyBytes.length; i++) {
            buffer[i] = keyBytes[i];
        }

        //根据给定的数组构造一个密钥
        SecretKeySpec key = new SecretKeySpec(buffer, "DES");
        return key;
    }

}
